package org.kl.auditsupervision.web.workflow;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.kl.auditsupervision.entity.fnd.AuditProDtl;
import org.kl.auditsupervision.entity.fnd.Org;
import org.kl.auditsupervision.repository.fnd.AuditProDtlDao;
import org.kl.auditsupervision.service.fnd.EmployeeService;
import org.kl.auditsupervision.service.fnd.OrgService;
import org.kl.bf.entity.basic.Role;
import org.kl.bf.entity.basic.User;
import org.kl.bf.entity.easyui.ComboBox;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.service.basic.RoleService;
import org.kl.bf.service.basic.UserService;
import org.kl.bf.web.base.BasicController;
import org.kl.bpm.entity.conf.BpmKvRecord;
import org.kl.bpm.service.conf.BpmKvPropService;
import org.kl.bpm.service.conf.BpmKvRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.MediaTypes;

/**
 * 获取审批人列表
 * 
 * @author cx
 * @date 2015年10月31日
 */
@Controller
@RequestMapping(value = "/wfl/assignee")
public class UserAssignController extends BasicController {
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserService userService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private BpmKvRecordService bpmKvRecordService;
	@Autowired
	private BpmKvPropService bpmKvPropService;
	
	@Autowired
	private AuditProDtlDao auditProDtlDao;

	@Autowired
	private HistoryService historyService;

	/**
	 * 获取某个角色下的用户
	 */
	@RequestMapping(value = "role/{roleNo}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String getRoleUsers(@PathVariable("roleNo") String roleNo) {
		List<ComboBox> combobox = new ArrayList<ComboBox>();
		try {
			Role role = roleService.getRoleByRoleNo(roleNo);
			List<User> users = userService.getUsersByRole(role.getId());
			for (User u : users) {
				ComboBox one = new ComboBox();
				one.setId(u.getId());
				one.setText(u.getTrueName());
				one.setValue(u.getId());
				combobox.add(one);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonMapper.toJson(combobox);
	}

	/**
	 * 获取某个角色下的用户,按部门过滤
	 */
	@RequestMapping(value = "roleByOrg/{roleNo}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String getRoleUsersByOrg(@PathVariable("roleNo") String roleNo,
			@RequestParam(value = "orgIds", defaultValue = "") String orgIds,
			ServletRequest request) {
		List<ComboBox> combobox = new ArrayList<ComboBox>();
		try {
			Role role = roleService.getRoleByRoleNo(roleNo);
			List<User> users = userService.getUsersByRoleAndOrg(role.getId(), orgIds,request);
			for (User u : users) {
				ComboBox one = new ComboBox();
				one.setId(u.getId());
				one.setText(u.getTrueName());
				one.setValue(u.getId());
				combobox.add(one);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonMapper.toJson(combobox);
	}

	/**
	 * 获取某个角色下的用户,按部门过滤 <主要找科长、副科长>
	 */
	@RequestMapping(value = "userByOrg/{roleNo}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String getUsersByOrg(@PathVariable("roleNo") String roleNo,
			@RequestParam(value = "taskId", defaultValue = "") String taskId,
			@RequestParam(value = "page", defaultValue = "1") int page,
			@RequestParam(value = "rows", defaultValue = "15") int pageSize,
			@RequestParam(value = "pageNumber", defaultValue = "0") int pageNumber,
			@RequestParam(value = "sortType", defaultValue = "") String sortType,
			@RequestParam(value = "orderby", defaultValue = "") String orderType,
			ServletRequest request) {
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		Map<String, Object> values = runtimeService.getVariables(task.getExecutionId());
		List<ComboBox> combobox = new ArrayList<ComboBox>();
		try {
			Org org = orgService.getOne(BasicController.getCurrentUserDeptId());
			String orgId = org.getRootOrgId();
			if (!values.isEmpty()) {
				if (values.containsKey("workFlowFlag") && values.get("workFlowFlag").equals("auditProDtl")) {
					
				}  else {
					
					
				}
			}
			Role role = roleService.getRoleByRoleNo(roleNo);
			List<User> users;
			users = userService.getUsersByRoleAndOrg(role.getId(),orgId, pageNumber,
					pageSize,request);
			int usersTotal = userService.getUsersByRoleIdAndOrgIdsCount(
					role.getId(),orgId, request);
			return EasyuiUtils.buildEasyuiGridJsonString(users,
					(int) usersTotal);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonMapper.toJson(combobox);
	}
	
	
	/**
	 * 获取某个角色下的用户,按部门过滤 <主要找科长、副科长>
	 */
	@RequestMapping(value = "userByOrgCombo/{roleNo}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String getUsersByOrgCombo(@PathVariable("roleNo") String roleNo,
			@RequestParam(value = "taskId", defaultValue = "") String taskId) {
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		Map<String, Object> values = runtimeService.getVariables(task.getExecutionId());
		List<ComboBox> combobox = new ArrayList<ComboBox>();
		try {
			Org org = orgService.getOne(BasicController.getCurrentUserDeptId());
			String orgId = org.getRootOrgId();
			if (!values.isEmpty()) {
				if (values.containsKey("workFlowFlag") && values.get("workFlowFlag").equals("auditProDtl")) {
					
				}  else {
					
					
				}
			}
			Role role = roleService.getRoleByRoleNo(roleNo);
			List<User> users;
			users = userService.getUsersByRoleAndOrg(role.getId(),orgId, 0,
					0,null);
			for (User u : users) {
				ComboBox one = new ComboBox();
				one.setId(u.getId());
				one.setText(u.getTrueName());
				one.setValue(u.getId());
				combobox.add(one);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonMapper.toJson(combobox);
	}
	
	/**
	 * 
	 */
	@RequestMapping(value = "userByTask/{TaskName}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String getUserByTask(@PathVariable("TaskName") String TaskName,
			@RequestParam(value = "taskId", defaultValue = "") String taskId,
			ServletRequest request) {
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		Map<String, Object> values = runtimeService.getVariables(task.getExecutionId());
		List<ComboBox> combobox = new ArrayList<ComboBox>();
		try {
			if (!values.isEmpty()) {
				//校外培训
				if (values.containsKey("workFlowFlag") && values.get("workFlowFlag").equals("training")) {
					BpmKvRecord bpmKvRecord = bpmKvRecordService.findByRef(task.getProcessInstanceId());// 获取审批信息
					/*List<BpmKvProp> bpmKvPropList=bpmKvPropService.findByRecordIdAndPropCodeOrderByCreateTimeDesc(bpmKvRecord.getId(),"checkboxWF");
					if(bpmKvPropList.size()>0){					
						
					}*/
				} 
				if(TaskName.equals("ASDept")){
					BpmKvRecord bpmKvRecord = bpmKvRecordService.findByRef(task.getProcessInstanceId());// 获取审批信息
					String businessid=bpmKvRecord.getBusinessId();
					AuditProDtl auditProDtl=auditProDtlDao.getOne(businessid);
					String orgId=auditProDtl.getOrg().getId();
					String roleNo = "SectionChief";
					//String orgNO=auditProDtl.getOrg().getOrgNo();
					//String roleNo = orgNO + "SectionChief";
					Role role = roleService.getRoleByRoleNo(roleNo);
					List<User> users = userService.getUsersByRoleAndOrg(role.getId(), orgId,request);					
					for (User u : users) {
						ComboBox one = new ComboBox();
						one.setId(u.getId());
						one.setText(u.getTrueName());
						one.setValue(u.getId());
						combobox.add(one);
					}					
				}if(TaskName.equals("ZRMake")){
					User user = new User();
					List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery()
							.processInstanceId(task.getProcessInstanceId()).orderByHistoricTaskInstanceStartTime().desc()
							.list();
					for (HistoricTaskInstance hiTask : historicTasks) {
						if (hiTask.getEndTime() == null) {

						} else {
							user = userService.getUser(hiTask.getAssignee());
							break;
						}
					}
					// List<User> users=new ArrayList<User>();
					// users.add(user) ;
					ComboBox one = new ComboBox();
					one.setId(user.getId());
					one.setText(user.getTrueName());
					one.setValue(user.getId());
					combobox.add(one);				
				}
				if(TaskName.equals("ASConfirm")){
					//“责任部门分管领导确认整改措施”不同意时返回责任人也用了该方法，请勿随意修改
					BpmKvRecord bpmKvRecord = bpmKvRecordService.findByRef(task.getProcessInstanceId());// 获取审批信息
					String businessid=bpmKvRecord.getBusinessId();
					AuditProDtl auditProDtl=auditProDtlDao.getOne(businessid);
					String employeeId=auditProDtl.getEmployee().getId();
					User user=userService.findUserByEmployeeId(employeeId);
					ComboBox one = new ComboBox();
					one.setId(user.getId());
					one.setText(user.getTrueName());
					one.setValue(user.getId());
					combobox.add(one);
				}
				if(TaskName.equals("ZRExe")){
					BpmKvRecord bpmKvRecord = bpmKvRecordService.findByRef(task.getProcessInstanceId());// 获取审批信息
					String businessid=bpmKvRecord.getBusinessId();
					AuditProDtl auditProDtl=auditProDtlDao.getOne(businessid);
					String superintendentId=auditProDtl.getSuperintendent().getId();
					User user=userService.findUserByEmployeeId(superintendentId);
					ComboBox one = new ComboBox();
					one.setId(user.getId());
					one.setText(user.getTrueName());
					one.setValue(user.getId());
					combobox.add(one);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonMapper.toJson(combobox);
	}
	
	
	
}
